//
//  XSJLoginVC.m
//  XSJ
//
//  Created by apple on 28.4.20.
//  Copyright © 2020 apple. All rights reserved.
//

#import "XSJLoginVC.h"
#import "SVProgressHUD.h"
#import "MJExtension.h"
#import "CQCountDownButton.h"
#import "UserInfoModel.h"
#import "JXLayoutButton.h"
#import "http_user.h"
#import "LoginTypeView.h"
#import "XSJRegisterVC.h"
#import "XSJTool.h"


@interface XSJLoginVC ()<LoginTypeViewDelegate>

@property (nonatomic, strong) UIImageView* icon1View;
@property (nonatomic, strong) UIImageView* icon2View;
@property (nonatomic, strong) UIImageView* icon3View;

@property (nonatomic, strong) UITextField *phoneTextField;
@property (nonatomic, strong) UITextField *vcodeTextField;

@property (nonatomic, strong) CQCountDownButton* vcodeButton;
@property (nonatomic, strong) UIButton *registerButton;

@property (nonatomic, strong) UIView* line1View;
@property (nonatomic, strong) UIView* line2View;

@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) LoginTypeView *typeView;

@property (nonatomic, strong) UIButton *testButton;
@property (nonatomic, strong) NSArray *testAccounts;
@property (nonatomic, strong) NSArray *testNames;
@property (nonatomic, strong) NSArray *testPasswords;

@property (nonatomic, strong) NSString *phone;

@end

@implementation XSJLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    [ZFTool isHiddenNavigationBarSeparatorLine:YES vc:self];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
    
    //点击隐藏键盘
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];[self.view addGestureRecognizer:singleTap];
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    [self.view endEditing:YES];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}


- (void)setupUI
{
    [self.view addSubview:self.icon1View];
    [self.view addSubview:self.icon2View];
    [self.view addSubview:self.icon3View];
    [self.view addSubview:self.line1View];
    [self.view addSubview:self.line2View];
    [self.view addSubview:self.phoneTextField];
    [self.view addSubview:self.vcodeTextField];
    [self.view addSubview:self.vcodeButton];
    [self.view addSubview:self.registerButton];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.typeView];
    
    [_icon1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(120);
        make.centerX.mas_equalTo(self.view);
    }];
    
    [_icon2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(65);
        make.top.equalTo(self->_icon1View.mas_bottom).offset(66);
        make.width.height.mas_equalTo(20);
    }];
    
    [_icon3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(65);
        make.top.equalTo(self->_icon2View.mas_bottom).offset(35);
        make.width.height.mas_equalTo(20);
    }];
    
    //控件优先级
    //    [self.icon1View setContentHuggingPriority:UILayoutPriorityRequired
    //                                      forAxis:UILayoutConstraintAxisHorizontal];
    //    [self.icon1View setContentCompressionResistancePriority:UILayoutPriorityRequired
    //                                                    forAxis:UILayoutConstraintAxisHorizontal];
    //    [self.usedPasswordTextField setContentHuggingPriority:UILayoutPriorityDefaultLow
    //                                                  forAxis:UILayoutConstraintAxisHorizontal];
    //    [self.usedPasswordTextField setContentCompressionResistancePriority:UILayoutPriorityDefaultLow
    //                                                                forAxis:UILayoutConstraintAxisHorizontal];
    
    
    [_phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_icon2View.mas_right).offset(15);
        make.top.bottom.equalTo(self->_icon2View);
        make.right.mas_equalTo(-15);
    }];
    
    [_vcodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_icon3View.mas_right).offset(10);
        make.top.bottom.equalTo(self->_icon3View);
        make.right.mas_equalTo(-100);
    }];
    
    [_vcodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->_line1View.mas_bottom).offset(17);
        make.right.mas_equalTo(-52);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(30);
    }];
    
    [_line1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(271);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self->_icon2View.mas_bottom).offset(10);
        make.height.mas_equalTo(1);
    }];
    
    [_line2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(271);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self->_icon3View.mas_bottom).offset(10);
        make.height.mas_equalTo(1);
    }];
    
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.width.mas_equalTo(285);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self->_line2View.mas_bottom).offset(10);
    }];
    
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(30);
        make.right.mas_equalTo(-26);
    }];
    
    [_typeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_bottom).offset(-160);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(80);
    }];
    
#ifdef APP_TEST
    [self.view addSubview:self.testButton];
    [_testButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.right.mas_equalTo(-20);
    }];
#else
    
#endif
    
}

//注册钮被点击
-(void)registerButtonDidClick
{
    //跳转到用户注册
    XSJRegisterVC* vc = [[XSJRegisterVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIImageView *)icon1View {
    if (_icon1View == nil) {
        _icon1View = [[UIImageView alloc] init];
        _icon1View.image = [UIImage imageNamed:@"New03"];
    }
    return _icon1View;
}

- (UIImageView *)icon2View {
    if (_icon2View == nil) {
        _icon2View = [[UIImageView alloc] init];
        _icon2View.image = [UIImage imageNamed:@"Phone"];
    }
    return _icon2View;
}

- (UIImageView *)icon3View {
    if (_icon3View == nil) {
        _icon3View = [[UIImageView alloc] init];
        _icon3View.image = [UIImage imageNamed:@"Verification"];
    }
    return _icon3View;
}

- (UITextField *)phoneTextField {
    if (_phoneTextField == nil) {
        _phoneTextField = [[UITextField alloc] init];
        _phoneTextField.placeholder = @"请输入手机号码";
        _phoneTextField.font = [UIFont systemFontOfSize:12];
        _phoneTextField.textColor = ColorHex(0x222222);
        // 重点
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入手机号码" attributes:
                                          @{NSForegroundColorAttributeName:ColorHex(0x999999),
                                            NSFontAttributeName:_phoneTextField.font
                                            }];
        _phoneTextField.attributedPlaceholder = attrString;
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        //改变删除的图标
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIButton *button =[_phoneTextField valueForKey:@"_clearButton"];
        [button setImage:[UIImage imageNamed:@"shangdiao"] forState:UIControlStateNormal];
    }
    return _phoneTextField;
}

- (UITextField *)vcodeTextField {
    if (_vcodeTextField == nil) {
        _vcodeTextField = [[UITextField alloc] init];
        _vcodeTextField.placeholder = @"请输入验证码";
        _vcodeTextField.font = [UIFont systemFontOfSize:12];
        _vcodeTextField.textColor = ColorHex(0x222222);
        // 重点
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:
                                          @{NSForegroundColorAttributeName:ColorHex(0x999999),
                                            NSFontAttributeName:_phoneTextField.font
                                            }];
        _vcodeTextField.attributedPlaceholder = attrString;
        _vcodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _vcodeTextField.keyboardType = UIKeyboardTypeNumberPad;
        //改变删除的图标
        _vcodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIButton *button =[_vcodeTextField valueForKey:@"_clearButton"];
        [button setImage:[UIImage imageNamed:@"shangdiao"] forState:UIControlStateNormal];
        
    }
    return _vcodeTextField;
}

- (UIButton *)registerButton {
    if (_registerButton == nil) {
        _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
        [_registerButton setTitleColor:ColorHex(0x0D0202) forState:UIControlStateNormal];
        _registerButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_registerButton addTarget:self action:@selector(registerButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}

- (UIView *)line1View {
    if (_line1View == nil) {
        _line1View = [[UIView alloc] init];
        _line1View.backgroundColor = ColorHexA(0x222222, 0.1);
    }
    return _line1View;
}

- (UIView *)line2View {
    if (_line2View == nil) {
        _line2View = [[UIView alloc] init];
        _line2View.backgroundColor = ColorHexA(0x222222, 0.1);
    }
    return _line2View;
}

- (UIButton *)loginButton {
    if (_loginButton == nil) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.backgroundColor = ColorHex(0xffffff);
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [_loginButton setBackgroundImage:[UIImage imageNamed:@"Sign2"] forState:UIControlStateNormal];
       // [_loginButton setTitleEdgeInsets:UIEdgeInsetsMake(-10, 0, 0, 0)];
        _loginButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _loginButton.layer.cornerRadius = 7.0f;
        _loginButton.clipsToBounds = YES;
        [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(loginButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

-(LoginTypeView*)typeView
{
    if (_typeView==nil)
    {
        _typeView = [[LoginTypeView alloc]initWithFrame:CGRectZero];
        _typeView.delegate = self;
    }
    
    return _typeView;
}

- (UIButton *)testButton {
    if (_testButton == nil) {
        _testButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_testButton setTitle:@"测试账号" forState:UIControlStateNormal];
        [_testButton setTitleColor:ColorHex(0x222222) forState:UIControlStateNormal];
        [_testButton addTarget:self action:@selector(testButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _testButton;
}


- (void)vcodeButtonDidClick
{
    NSString* phone = _phoneTextField.text;

    ZWeakSelf
    [http_user sendCode:phone type:@"login" success:^(id responseObject)
     {
         [weakSelf verifycode_ok:responseObject];

     } failure:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:error.domain];
     }];
}

-(void)verifycode_ok:(id)responseObject
{
    [SVProgressHUD showSuccessWithStatus:@"发送成功"];
    
}

- (CQCountDownButton *)vcodeButton
{
    if (_vcodeButton == nil) {
        _vcodeButton = [CQCountDownButton buttonWithType:UIButtonTypeCustom];
        [_vcodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _vcodeButton.backgroundColor = ColorHex(0xffffff);
        [_vcodeButton setTitleColor:ColorHex(0xCC88F0) forState:UIControlStateNormal];
        _vcodeButton.titleLabel.font = [UIFont systemFontOfSize:12];
        _vcodeButton.layer.borderWidth = 1.0f;
        _vcodeButton.layer.borderColor = ColorHex(0xCC88F0).CGColor;
        _vcodeButton.layer.cornerRadius = 5.0f;
        _vcodeButton.clipsToBounds = YES;
        //        [_vcodeButton addTarget:self action:@selector(vcodeButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
        __weak typeof(self) weakSelf = self;
        [_vcodeButton configDuration:60 buttonClicked:^{
            //========== 按钮点击 ==========//
            if ( kStringIsEmpty(weakSelf.phoneTextField.text) )
            {
                [SVProgressHUD showInfoWithStatus:@"请输入手机号码"];
                weakSelf.vcodeButton.enabled = YES;
                return;
            }

            if ( [XSJTool isPhoneNumber:weakSelf.phoneTextField.text]==NO )
            {
                [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
                weakSelf.vcodeButton.enabled = YES;
                return;
            }

            [weakSelf.vcodeButton startCountDown];
            [weakSelf vcodeButtonDidClick];
        } countDownStart:^{
            //========== 倒计时开始 ==========//
            NSLog(@"倒计时开始");
        } countDownUnderway:^(NSInteger restCountDownNum) {
            //========== 倒计时进行中 ==========//
            NSString *title = [NSString stringWithFormat:@"%ldS", restCountDownNum];
            [weakSelf.vcodeButton setTitle:title forState:UIControlStateNormal];
        } countDownCompletion:^{
            //========== 倒计时结束 ==========//
            [weakSelf.vcodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            NSLog(@"倒计时结束");
        }];
    }
    return _vcodeButton;
}


//登录按钮被点击
- (void)loginButtonDidClick
{
    NSString* phone = _phoneTextField.text;
    NSString* code = _vcodeTextField.text;
    
    if (kStringIsEmpty(phone))
    {
        [SVProgressHUD showInfoWithStatus:@"请输入手机号"];
        return;
    }
    if ( [XSJTool isPhoneNumber:phone]==NO )
    {
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        return;
    }

    if (kStringIsEmpty(code))
    {
        [SVProgressHUD showInfoWithStatus:@"请输入验证码"];
        return;
    }

    self.phone = phone;
    [self toLogin:phone password:code];
}

- (void)testButtonDidClick
{
//    NSMutableArray* array = [[NSMutableArray alloc]init];
//    for (int i=0; i<self.testNames.count; i++)
//    {
//        NSString* str = [self.testNames objectAtIndex:i];
//        PopoverAction *action = [PopoverAction actionWithTitle:str handler:^(PopoverAction *action)
//                                 {
//                                     NSString* username = [self.testAccounts objectAtIndex:i];
//                                     NSString* password = [self.testPasswords objectAtIndex:i];
//                                     [self toLogin:username password:password];
//                                 }];
//        [array addObject:action];
//    }
//    PopoverView *popoverView = [PopoverView popoverView];
//    popoverView.style = PopoverViewStyleDark;
//    [popoverView showToView:self.testButton withActions:array];
}

//登录
-(void)toLogin:(NSString*)username password:(NSString*)password
{
    ZWeakSelf
    [SVProgressHUD showWithStatus:@"正在登录"];
    [http_user login:username password:password success:^(id responseObject)
     {
         [SVProgressHUD showSuccessWithStatus:@"登录成功"];
         [weakSelf toLogin_ok:responseObject];
     } failure:^(NSError *error) {
         [SVProgressHUD showInfoWithStatus:error.domain];
         if (error.code==500006)
         {
             [weakSelf registerButtonDidClick];
         }
     }];
}

-(void)toLogin_ok:(id)responseObject
{
    if(kObjectIsEmpty(responseObject))
    {
        return;
    }
    
    UserInfoModel* userInfo = nil;
    NSDictionary* dict = [responseObject objectForKey:@"loginPlateUser"];
    if (!kObjectIsEmpty(dict))
    {
        userInfo = [UserInfoModel mj_objectWithKeyValues:dict];
    }
    
    NSString* token = [responseObject objectForKey:@"token"];
    if (!kStringIsEmpty(token))
    {
        userInfo.token = token;
    }
    
    [userInfo saveUserInfo];
    //登录成功通知
    [[NSNotificationCenter defaultCenter] postNotificationName:UserLoginRegisterNotification object:self];

//    //登录网易云
//    [[[NIMSDK sharedSDK] loginManager] login:userInfo.ID token:userInfo.chatToken completion:^(NSError * _Nullable error) {
//
//        if (!error)
//        {
//            // 登录成功跳转
//            DLog(@"登录网易云成功");
//        } else
//        {
//            DLog(@"登录网易云失败:%@", error.domain);
//            // 登录失败跳转
//        }
//    }];
}



/**
 登录类型view按扭被点击
 
 @param type 1:微信 2:QQ 3:新浪 4:手机
 */
- (void)LoginTypeViewDidClick:(int)type
{
    //[JumpVCTool to_ThirdpartyLogin:type srcVC:self];
}



- (NSArray *)testNames {
    if (_testNames == nil) {
        _testNames = @[
                       @"测试1",
                       @"测试2",
                       @"测试3"
                       ];
    }
    return _testNames;
}

- (NSArray *)testAccounts {
    if (_testAccounts == nil) {
        _testAccounts = @[
                          @"13122334455",
                          @"13726776665",
                          @"13726776666"
                          ];
    }
    return _testAccounts;
}

- (NSArray *)testPasswords {
    if (_testPasswords == nil) {
        _testPasswords = @[
                          @"1111",
                          @"5682",
                          @"4819"
                          ];
    }
    return _testPasswords;
}


@end
